package com.ifonly.common.typeconverter.impl;

import com.ifonly.common.typeconverter.Converter;
import com.ifonly.common.typeconverter.TypeConversionException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 20:09
 * @since JDK 1.6
 */
public class CharacterConverter implements Converter<Character> {
    @Override
    public Character convert(Object value) {
        if (value == null) {
            return null;
        }
        if (value.getClass() == Character.class) {
            return (Character) value;
        }
        if (value instanceof Number) {
            char c = (char) ((Number) value).intValue();
            return c;
        }
        try {
            String s = value.toString();
            if (s.length() != 1) {
                s = s.trim();
                try {
                    char c = (char) Integer.parseInt(s);
                    return c;
                } catch (NumberFormatException e) {
                    throw new TypeConversionException(value, e);
                }
            }
            return s.charAt(0);
        } catch (IndexOutOfBoundsException e) {
            throw new TypeConversionException(value, e);
        }
    }
}
